import os
from datetime import datetime
import numpy as np
import trimesh


def save_geometry(mesh: trimesh.Trimesh, filename: str, alpha: float = 45.0, C: float = 12.0, S1: float = 8.0,
                  S2: float = 12.0, H1: float = 2.0, H2: float = 1.0):
    """保存几何体到文件"""
    try:
        # 创建专门的网格文件夹
        mesh_dir = os.path.join(os.getcwd(), "output_models", "几何体网格文件")
        os.makedirs(mesh_dir, exist_ok=True)
        print(f"\n创建网格文件夹: {mesh_dir}")

        # 生成带时间戳的文件名
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

        # 保存多种格式
        saved_files = []

        # 1. 保存STL格式
        try:
            stl_filename = f"mesh_alpha_{alpha:.1f}_C{C:.1f}_{timestamp}.stl"
            stl_path = os.path.join(mesh_dir, stl_filename)
            mesh.export(stl_path, file_type='stl')
            print(f"✓ STL模型已保存: {stl_path}")
            print(f"  - 文件大小: {os.path.getsize(stl_path) / 1024:.1f} KB")
            saved_files.append(stl_path)
        except Exception as e:
            print(f"✗ STL保存失败: {str(e)}")

        # 2. 保存网格统计信息到文本文件
        try:
            stats_filename = f"mesh_stats_alpha_{alpha:.1f}_C{C:.1f}_{timestamp}.txt"
            stats_path = os.path.join(mesh_dir, stats_filename)

            with open(stats_path, 'w', encoding='utf-8') as f:
                f.write(f"路堤边坡整体几何体网格统计信息\n")
                f.write(f"=" * 50 + "\n")
                f.write(f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
                f.write(f"参数信息:\n")
                f.write(f"  - 坡脚角度: {alpha}°\n")
                f.write(f"  - 长方体长度(C): {C}m\n")
                f.write(f"  - 梯形台顶部长度(S1): {S1}m\n")
                f.write(f"  - 梯形台底部长度(S2): {S2}m\n")
                f.write(f"  - 长方体高度(H2): {H2}m\n")
                f.write(f"  - 梯形台高度(H1): {H1}m\n")
                f.write(f"  - 几何体类型: 整体几何体（长方体+梯形台无缝连接）\n")
                f.write(f"\n网格信息:\n")
                f.write(f"  - 顶点数量: {len(mesh.vertices)}\n")
                f.write(f"  - 面片数量: {len(mesh.faces)}\n")
                f.write(f"  - 边数量: {len(mesh.edges)}\n")
                f.write(f"  - 体积: {mesh.volume:.4f} m³\n")
                f.write(f"  - 表面积: {mesh.area:.4f} m²\n")
                f.write(f"  - 边界框: {mesh.bounds}\n")
                f.write(f"  - 重心: {mesh.center_mass}\n")
                f.write(f"\n网格质量:\n")
                try:
                    qualities = trimesh.triangles.quality(mesh.triangles)
                    edge_lengths = mesh.edges_unique_length
                    f.write(f"  - 平均边长: {np.mean(edge_lengths):.4f} ± {np.std(edge_lengths):.4f} m\n")
                    f.write(f"  - 三角形质量: {np.mean(qualities):.2%} (0-100%, 越高越好)\n")
                    f.write(f"  - 最小质量三角形: {np.min(qualities):.2%}\n")
                    f.write(f"  - 最大质量三角形: {np.max(qualities):.2%}\n")
                except Exception as e:
                    f.write(f"  - 质量评估失败: {str(e)}\n")
                f.write(f"\n保存的文件:\n")
                for i, file_path in enumerate(saved_files, 1):
                    f.write(f"  {i}. {os.path.basename(file_path)}\n")

            print(f"✓ 网格统计信息已保存: {stats_path}")
            print(f"  - 文件大小: {os.path.getsize(stats_path) / 1024:.1f} KB")
            saved_files.append(stats_path)
        except Exception as e:
            print(f"✗ 统计信息保存失败: {str(e)}")

        # 尝试打开网格文件夹
        try:
            os.startfile(mesh_dir)
            print("已自动打开网格文件夹")
        except:
            print(f"请手动打开目录查看文件: {mesh_dir}")

        return saved_files

    except Exception as e:
        print(f"保存网格文件时发生错误: {str(e)}")
        import traceback
        traceback.print_exc()
        return []
